package com.jeeplus.modules.common.excel.common.validator.impl.base;

import com.jeeplus.modules.common.excel.common.anno.base.IsPattern;
import com.jeeplus.modules.common.excel.common.validator.abs.AbstractValidator;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wang.yishu
 * @version 1.0
 * @className IsPatternValidator
 * @description TODO
 * @date 2022/8/2 12:19
 */
public class IsPatternValidator extends AbstractValidator {

    private IsPattern isPattern;

    @Override
    public boolean canValidate(Field field) {
        isPattern = field.getDeclaredAnnotation(IsPattern.class);
        return isPattern != null;
    }

    @Override
    public String toValidate(Object entity, Field field) {
        field.setAccessible(true);
        try {
            Object value = field.get(entity);
            if (value == null) return null;
            if (value instanceof String) {
                String valueStr = value.toString();
                String regex = isPattern.regex();
                Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
                Matcher m = p.matcher(valueStr);
                if (!m.matches()) {
                    return isPattern.msg();
                }
            } else {
                return null;
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
